package com.tl.boot.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tl.boot.common.constants.RedisConstant;
import com.tl.boot.common.config.PermissionParamConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * com.tl.boot.common.utils -- PermissionUtil
 * Description:
 * Created by joshua_liu <a href="mailto:joshualwork@163.com"></a>
 * On 2019/9/12 14:49
 */
@Component
public class PermissionUtil {
    private static RedisUtil redisUtil;
    private static PermissionParamConfig permissionParamConfig;


    @Autowired
    public void setPermissionConfig(RedisUtil redisUtil, PermissionParamConfig permissionParamConfig) {
        PermissionUtil.redisUtil = redisUtil;
        PermissionUtil.permissionParamConfig = permissionParamConfig;
    }

    public static JSONObject getPermissionInfo(Long userId) {
        if (userId != null) {
            try {
                String encryptPermissionStr = redisUtil.get(String.format(RedisConstant.PERMISSION_KEY, userId));
                String decryptStr = null;
                decryptStr = AesUtil.decrypt(encryptPermissionStr, permissionParamConfig.getSalt());
                return JSON.parseObject(decryptStr);
            } catch (Exception e) {
                LogUtil.error(e);
                return null;
            }
        }
        return null;
    }

    public static void setEncryptPermissionInfo(Long userId, JSONObject permissionInfo) {
        if (userId != null && permissionInfo != null) {
            String encryptPermissionInfo = AesUtil.encrypt(permissionInfo.toJSONString(), permissionParamConfig.getSalt());
            redisUtil.set(String.format(RedisConstant.PERMISSION_KEY, userId), encryptPermissionInfo, permissionParamConfig.getValidTime());
        }
    }

    public static void invalidatePermissionInfo(Long userId) {
        if (userId != null) {
            redisUtil.set(String.format(RedisConstant.PERMISSION_KEY, userId), "", TimeUnit.MILLISECONDS.toSeconds(1));
        }
    }
}
